package com.pan.api.format.impl.markdown;


import com.pan.api.entity.ArgumentInformation;
import com.pan.api.entity.MethodInformation;
import com.pan.api.format.ArgumentFormat;
import com.pan.api.format.MethodFormat;
import com.pan.api.utils.PanJsonConvertUtil;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public final class MarkdownMethodFormat
        extends MethodFormat
    implements PanJsonConvertUtil
{
    public MarkdownMethodFormat(ArgumentFormat parameterStandardization) {
        super(parameterStandardization);
    }

    {//methodName,comment,url,requestType,isJsonStr,returnType,argListStr
        String template =
                """
                    
                  **Method**: {methodName}  
                  - comment: {comment}  
                  - url: url/m00/{aaa}  
                  - request type: {requestType}  
                  - is json: {isJson}  
                  - **return type**   
                    - <details><summary style="color: gray">arguments</summary>
                    
                      ```
                      {returnType}
                      ```  
                    </details>                  
                  - **arguments**:  
                    
                    - <details><summary style="color: gray">arguments</summary>
                    {argListStr}  
                    </details>
                """;
        String regex = "\\{\\w+?\\}";
        initialization(template,regex);
    }

    @Override
    public String convert(MethodInformation methodInformation) {
        String methodName = methodInformation.getMethodName();
        String comment = methodInformation.getComment();
        String url = methodInformation.getUrl();
        String requestType = Arrays.toString(methodInformation.getRequestType());
        String returnType = convertToJson(methodInformation.getReturnType());
        returnType = returnType.strip().replaceAll("\n","\n      ");
        String isJsonStr = methodInformation.isJsonXml()?"true":"false";
        List<ArgumentInformation> argList = methodInformation.getArgList().stream()
                .sorted(Comparator.comparing(ai->ai.getParamName())).toList();
        String argListStr = argList.isEmpty()?"":argList.stream().map(argumentInformation -> super.argumentFormat.convert(argumentInformation))
                .reduce((previous, current)->previous.concat(current)).get();

        return replace(methodName,comment,url,requestType,isJsonStr,returnType,argListStr);
    }
}
